import Vue from 'vue'
import axios from 'axios'
import { getToken } from '@/utils/token.js'
import { removeToken } from '@/utils/token.js'

axios.defaults.baseURL = process.env.VUE_APP_BASEURL
axios.defaults.withCredentials = true

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const token = getToken()
    if (token) {
      config.headers.token = token
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  function (response) {
    if (response.data.code === 206) {
      removeToken()

      router.push('/login')
    }
    return response
  },
  function (error) {
    return Promise.reject(error)
  }
)
Vue.prototype.$axios = axios
